﻿using App.Domain.Model;
using App.MVCClient.Controllers;
using App.MVCClient.Models;
using System;
using System.Linq;
using System.Web.Mvc;

namespace App.MVCClient.Areas.User.Controllers
{
    public class AddressController : BaseController
    {
        //
        // GET: /User/Address
        [HttpGet]
        public ActionResult Index(string AddressTypeFilter = null, string DomainIdFilter = null)
        {
            int ownerId;
            Int32.TryParse(DomainIdFilter, out ownerId);
            AddressIndex ai = new AddressIndex()
            {
                AddressList = bal.GetAddresses(AddressTypeFilter, ownerId).Select(addr => new AddressDTO(addr))
            };
            return View(ai);
        }

        //
        // GET: /User/Address/Create
        [HttpGet]
        public ActionResult Create(int? id = null)
        {
            AddressDTO address;
            if (id.HasValue)
                address = new AddressDTO(bal.GetAddress(id.Value));
            else
                address = new AddressDTO() { AddressLine1 = "7-2-422, SRT 201" };
            return View(address);
        }

        //
        // POST: /User/Address/Create

        [HttpPost]
        public ActionResult Create(AddressDTO viewModel)
        {
            try
            {
                if (viewModel.AddressID <= 0)
                {
                    // TODO: Add insert logic here
                    StateProvince state = bal.GetState(viewModel.CountryCode, viewModel.StateProvinceCode);

                    bal.CreateAddress(viewModel.GetModel(state));
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View(viewModel);
            }
        }
    }
}
